<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 响应式数据
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const isEdit = ref(false);
const selectedStaff = ref<any>(null);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  experience: '',
});

// 人员表单
const staffForm = reactive({
  name: '',
  phone: '',
  idCard: '',
  joinDate: null,
  experience: '',
  status: 'active',
  specialties: [],
  remarks: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 人员数据
const staff = ref([
  {
    id: '1',
    name: '张阿姨',
    phone: '13800138001',
    idCard: '110101199001011234',
    joinDate: dayjs('2022-01-15'),
    experience: '3年',
    status: 'active',
    rating: 4.5,
    specialties: ['regular', 'deep'],
    todayTasks: 3,
    weekTasks: 15,
    monthTasks: 45,
    completionRate: 95,
    remarks: '工作认真负责，客户评价良好',
  },
  {
    id: '2',
    name: '李阿姨',
    phone: '13800138002',
    idCard: '110101199002022345',
    joinDate: dayjs('2022-03-20'),
    experience: '2年',
    status: 'active',
    rating: 4.2,
    specialties: ['regular', 'checkout'],
    todayTasks: 2,
    weekTasks: 12,
    monthTasks: 38,
    completionRate: 92,
    remarks: '擅长退租清洁',
  },
  {
    id: '3',
    name: '王阿姨',
    phone: '13800138003',
    idCard: '110101199003033456',
    joinDate: dayjs('2021-08-10'),
    experience: '5年',
    status: 'leave',
    rating: 4.8,
    specialties: ['deep', 'emergency'],
    todayTasks: 0,
    weekTasks: 8,
    monthTasks: 25,
    completionRate: 98,
    remarks: '经验丰富，技术过硬',
  },
  {
    id: '4',
    name: '赵阿姨',
    phone: '13800138004',
    idCard: '110101199004044567',
    joinDate: dayjs('2023-01-05'),
    experience: '1年',
    status: 'active',
    rating: 4,
    specialties: ['regular'],
    todayTasks: 4,
    weekTasks: 18,
    monthTasks: 52,
    completionRate: 88,
    remarks: '新人，学习能力强',
  },
]);

// 统计信息
const statistics = computed(() => {
  const totalStaff = staff.value.length;
  const activeStaff = staff.value.filter((s) => s.status === 'active').length;
  const todayAttendance = staff.value.filter(
    (s) => s.status === 'active',
  ).length;
  const avgRating =
    staff.value.reduce((sum, s) => sum + s.rating, 0) / staff.value.length;

  return {
    totalStaff,
    activeStaff,
    todayAttendance,
    avgRating: avgRating.toFixed(1),
  };
});

// 过滤后的人员
const filteredStaff = computed(() => {
  let result = staff.value;

  if (searchForm.name) {
    result = result.filter((s) => s.name.includes(searchForm.name));
  }
  if (searchForm.status) {
    result = result.filter((s) => s.status === searchForm.status);
  }
  if (searchForm.experience) {
    result = result.filter((s) => s.experience === searchForm.experience);
  }

  return result;
});

// 表格列定义
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '工作经验',
    dataIndex: 'experience',
    key: 'experience',
    width: 100,
  },
  {
    title: '评分',
    dataIndex: 'rating',
    key: 'rating',
    width: 120,
  },
  {
    title: '专长领域',
    dataIndex: 'specialties',
    key: 'specialties',
    width: 200,
  },
  {
    title: '工作负荷',
    dataIndex: 'workload',
    key: 'workload',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 工具函数
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'success',
    inactive: 'default',
    leave: 'warning',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '在职',
    inactive: '离职',
    leave: '请假',
  };
  return statusMap[status] || status;
};

const getSpecialtyText = (specialty: string) => {
  const specialtyMap: Record<string, string> = {
    regular: '日常清洁',
    deep: '深度清洁',
    checkout: '退租清洁',
    emergency: '紧急清洁',
  };
  return specialtyMap[specialty] || specialty;
};

const formatDate = (date: any) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '';
  datedayjs.format;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  console.log('搜索条件:', searchForm);
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: '',
    experience: '',
  });
  pagination.current = 1;
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};

const handleView = (record: any) => {
  selectedStaff.value = record;
  showDetailModal.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  selectedStaff.value = record;
  Object.assign(staffForm, {
    name: record.name,
    phone: record.phone,
    idCard: record.idCard,
    joinDate: record.joinDate,
    experience: record.experience,
    status: record.status,
    specialties: record.specialties,
    remarks: record.remarks,
  });
  showAddModal.value = true;
};

const handleLeave = (record: any) => {
  message.success(`${record.name} 已请假`);
};

const handleReturn = (record: any) => {
  message.success(`${record.name} 已复工`);
};

const handleDelete = (record: any) => {
  message.success(`${record.name} 已删除`);
};

const handleSave = () => {
  if (!staffForm.name || !staffForm.phone) {
    message.error('请填写完整的人员信息');
    return;
  }

  if (isEdit.value) {
    message.success('人员信息更新成功');
  } else {
    message.success('人员添加成功');
  }

  showAddModal.value = false;
  handleCancel();
};

const handleCancel = () => {
  Object.assign(staffForm, {
    name: '',
    phone: '',
    idCard: '',
    joinDate: null,
    experience: '',
    status: 'active',
    specialties: [],
    remarks: '',
  });
  isEdit.value = false;
  selectedStaff.value = null;
};

// 初始化
onMounted(() => {
  console.log('清洁人员管理页面已加载');
});
</script>

<template>
  <div class="cleaning-staff">
    <div class="page-header">
      <h2>清洁人员管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:user-add-outlined" />
        添加人员
      </Button>
    </div>

    <!-- 搜索表单 -->
    <Card :bordered="false" class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="姓名">
          <Input
            :value="searchForm.name"
            placeholder="请输入姓名"
            style="width: 120px"
            @input="(e) => (searchForm.name = e.target.value)"
          />
        </FormItem>
        <FormItem label="状态">
          <Select
            :value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
            allow-clear
            @change="(value) => (searchForm.status = value)"
          >
            <SelectOption value="active">在职</SelectOption>
            <SelectOption value="inactive">离职</SelectOption>
            <SelectOption value="leave">请假</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="工作经验">
          <Select
            :value="searchForm.experience"
            placeholder="请选择经验"
            style="width: 140px"
            allow-clear
            @change="(value) => (searchForm.experience = value)"
          >
            <SelectOption value="0-1">0-1年</SelectOption>
            <SelectOption value="1-3">1-3年</SelectOption>
            <SelectOption value="3-5">3-5年</SelectOption>
            <SelectOption value="5+">5年以上</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总人数"
          :value="statistics.totalStaff"
          color="#1890ff"
          icon="ant-design:team-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在职人员"
          :value="statistics.activeStaff"
          color="#52c41a"
          icon="ant-design:user-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日出勤"
          :value="statistics.todayAttendance"
          color="#faad14"
          icon="ant-design:calendar-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均评分"
          :value="statistics.avgRating"
          color="#722ed1"
          icon="ant-design:star-outlined"
        />
      </Col>
    </Row>

    <!-- 人员列表 -->
    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredStaff"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'rating'">
            <div class="rating-info">
              <span class="rating-score">{{ record.rating }}</span>
              <div class="rating-stars">
                <IconifyIcon
                  v-for="i in 5"
                  :key="i"
                  :icon="
                    i <= record.rating
                      ? 'ant-design:star-filled'
                      : 'ant-design:star-outlined'
                  "
                  :style="{ color: i <= record.rating ? '#faad14' : '#d9d9d9' }"
                />
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'specialties'">
            <div class="specialties">
              <Tag
                v-for="specialty in record.specialties"
                :key="specialty"
                size="small"
                color="blue"
              >
                {{ getSpecialtyText(specialty) }}
              </Tag>
            </div>
          </template>
          <template v-else-if="column.key === 'workload'">
            <div class="workload-info">
              <div class="workload-item">
                <span class="label">今日：</span>
                <span class="value">{{ record.todayTasks }}</span>
              </div>
              <div class="workload-item">
                <span class="label">本周：</span>
                <span class="value">{{ record.weekTasks }}</span>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="handleEdit(record)">
                编辑
              </Button>
              <Button
                v-if="record.status === 'active'"
                type="link"
                size="small"
                @click="handleLeave(record)"
              >
                请假
              </Button>
              <Button
                v-if="record.status === 'leave'"
                type="link"
                size="small"
                @click="handleReturn(record)"
              >
                复工
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 添加/编辑人员弹窗 -->
    <Modal
      :open="showAddModal"
      :title="isEdit ? '编辑人员' : '添加人员'"
      width="600px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form :model="staffForm" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="姓名" name="name" required>
              <Input
                :value="staffForm.name"
                placeholder="请输入姓名"
                @input="(e) => (staffForm.name = e.target.value)"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="联系电话" name="phone" required>
              <Input
                :value="staffForm.phone"
                placeholder="请输入联系电话"
                @input="(e) => (staffForm.phone = e.target.value)"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="身份证号" name="idCard">
              <Input
                :value="staffForm.idCard"
                placeholder="请输入身份证号"
                @input="(e) => (staffForm.idCard = e.target.value)"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="入职日期" name="joinDate">
              <DatePicker
                :value="staffForm.joinDate"
                style="width: 100%"
                placeholder="请选择入职日期"
                @change="(value) => (staffForm.joinDate = value)"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="工作经验" name="experience">
              <Select
                :value="staffForm.experience"
                placeholder="请选择工作经验"
                style="width: 100%"
                @change="(value) => (staffForm.experience = value)"
              >
                <SelectOption value="0-1">0-1年</SelectOption>
                <SelectOption value="1-3">1-3年</SelectOption>
                <SelectOption value="3-5">3-5年</SelectOption>
                <SelectOption value="5+">5年以上</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="状态" name="status">
              <Select
                :value="staffForm.status"
                placeholder="请选择状态"
                style="width: 100%"
                @change="(value) => (staffForm.status = value)"
              >
                <SelectOption value="active">在职</SelectOption>
                <SelectOption value="inactive">离职</SelectOption>
                <SelectOption value="leave">请假</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="专长领域" name="specialties">
          <Select
            :value="staffForm.specialties"
            mode="multiple"
            placeholder="请选择专长领域"
            style="width: 100%"
            @change="(value) => (staffForm.specialties = value)"
          >
            <SelectOption value="regular">日常清洁</SelectOption>
            <SelectOption value="deep">深度清洁</SelectOption>
            <SelectOption value="checkout">退租清洁</SelectOption>
            <SelectOption value="emergency">紧急清洁</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            :value="staffForm.remarks"
            placeholder="请输入备注信息"
            :rows="3"
            @input="(e) => (staffForm.remarks = e.target.value)"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 人员详情弹窗 -->
    <Modal
      :open="showDetailModal"
      title="人员详情"
      width="700px"
      :footer="null"
    >
      <div v-if="selectedStaff" class="staff-detail">
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <span class="label">姓名：</span>
                <span class="value">{{ selectedStaff.name }}</span>
              </div>
              <div class="detail-item">
                <span class="label">联系电话：</span>
                <span class="value">{{ selectedStaff.phone }}</span>
              </div>
              <div class="detail-item">
                <span class="label">身份证号：</span>
                <span class="value">{{
                  selectedStaff.idCard || '未填写'
                }}</span>
              </div>
              <div class="detail-item">
                <span class="label">状态：</span>
                <span class="value">
                  <Tag :color="getStatusColor(selectedStaff.status)">
                    {{ getStatusText(selectedStaff.status) }}
                  </Tag>
                </span>
              </div>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-section">
              <h4>工作信息</h4>
              <div class="detail-item">
                <span class="label">入职日期：</span>
                <span class="value">{{
                  formatDate(selectedStaff.joinDate)
                }}</span>
              </div>
              <div class="detail-item">
                <span class="label">工作经验：</span>
                <span class="value">{{ selectedStaff.experience }}</span>
              </div>
              <div class="detail-item">
                <span class="label">评分：</span>
                <span class="value">{{ selectedStaff.rating }}分</span>
              </div>
              <div class="detail-item">
                <span class="label">专长：</span>
                <span class="value">
                  <Tag
                    v-for="specialty in selectedStaff.specialties"
                    :key="specialty"
                    size="small"
                    color="blue"
                  >
                    {{ getSpecialtyText(specialty) }}
                  </Tag>
                </span>
              </div>
            </div>
          </Col>
        </Row>
        <div class="detail-section">
          <h4>工作统计</h4>
          <Row :gutter="16">
            <Col :span="6">
              <div class="stat-card">
                <div class="stat-title">今日任务</div>
                <div class="stat-value">{{ selectedStaff.todayTasks }}</div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-card">
                <div class="stat-title">本周任务</div>
                <div class="stat-value">{{ selectedStaff.weekTasks }}</div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-card">
                <div class="stat-title">本月任务</div>
                <div class="stat-value">{{ selectedStaff.monthTasks }}</div>
              </div>
            </Col>
            <Col :span="6">
              <div class="stat-card">
                <div class="stat-title">完成率</div>
                <div class="stat-value">
                  {{ selectedStaff.completionRate }}%
                </div>
              </div>
            </Col>
          </Row>
        </div>
        <div v-if="selectedStaff.remarks" class="detail-section">
          <h4>备注</h4>
          <div class="detail-item">
            <span class="value">{{ selectedStaff.remarks }}</span>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.cleaning-staff {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.rating-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-score {
  font-weight: 600;
  color: #faad14;
}

.rating-stars {
  display: flex;
  gap: 2px;
}

.specialties {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.workload-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.workload-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.workload-item .label {
  color: #666;
}

.workload-item .value {
  font-weight: 600;
  color: #1890ff;
}

.staff-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin-bottom: 12px;
  color: #1f2937;
  font-weight: 600;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.detail-item .value {
  flex: 1;
  color: #1f2937;
}

.stat-card {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}
</style>
